import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, usePageResponseSuccess, useResponseSuccess, useResponseError } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    // 返回数据的列
    const columns = ['msdsNo', 'chemNameCn', 'component', 'fillDate'];
    let queryString;
    const args = [];

    // 获取查询参数
    const { page, pageSize, msdsNo, component, sortBy, sortOrder } = await getQuery(event);
    // 处理排序字段和排序顺序
    let finalSortBy = sortBy || 'msdsNo';
    let finalSortOrder = sortOrder || 'ASC';

    // 根据 msdsNo 和 component 构建查询语句
    if (!msdsNo && !component) {
      // 如果 msdsNo 和 component 均为空，则查询所有数据
      queryString = `SELECT ${columns.join(', ')} FROM msdsdata ORDER BY ? ?`;
    } else {
      // 如果 msdsNo、component 有一个不为空或者都不为空时，查询满足要求的数据
      let whereClause = [];
      if (msdsNo) {
        whereClause.push('msdsNo = ?');
        args.push(msdsNo);
      }
      if (component && component.length > 0) {
        const componentConditions = component.map(() => 'JSON_CONTAINS(component, JSON_QUOTE(?))').join(' AND ');
        whereClause.push(componentConditions);
        args.push(...component);
      }
      queryString = `SELECT ${columns.join(', ')} FROM msdsdata WHERE ${whereClause.join(' AND ')} ORDER BY ? ?`;
    }
    // 合并排序的参数
    args.push(finalSortBy, finalSortOrder);

    // 调用 queryDatabase 函数执行操作
    const results = <any[]>await queryDatabase(queryString, args);
    if (results.length <= 0) {
      return useResponseSuccess({ message: '未查询到匹配的数据' });
    } else {
      // 将results.component字段["甲烷","乙烷"]转换为甲烷,乙烷
      const processedResults = results.map((item: any) => {
        try {
          const componentArray = Array.isArray(item.component) ? item.component : JSON.parse(item.component || '[]');
          return {
            ...item,
            component: componentArray.join('、'),
          };
        } catch (error) {
          // 转换失败时保留原始值（或根据需求处理错误）
          console.error('component字段转换失败:', error);
          return {
            ...item,
            component: '数据格式错误',
          };
        }
      });
      return usePageResponseSuccess(page as string, pageSize as string, processedResults);
    }
  } catch (error) {
    return useResponseError(error.message);
  }
});
